/* AccountsEditorActivity.java
 *
 * Copyright 2011 Aleksey Konovalov
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

package org.jimm.app;

import java.util.ArrayList;
import java.util.List;

import org.jimm.app.util.Pair;
import org.jimm.db.JimmDatabase.Accounts;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

public class AccountsEditorActivity extends Activity {

	public static final String LOG_TAG = "Jimm:AccountEditor";
	private class AccountsObserver extends ContentObserver {

		public AccountsObserver(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			accountsListAdapter.updateItems();
		}

	}

	private class AccountsAdapter extends BaseAdapter {

		private final LayoutInflater inflater;
		// ������� � ��/��������
		private List<Pair<Integer, String>> items = new ArrayList<Pair<Integer, String>>();

		AccountsAdapter(Context context) {
			inflater = LayoutInflater.from(context);
			updateItems();
		}

		public void updateItems() {
			synchronized (items) {
				items.clear();
				Cursor c = managedQuery(Accounts.CONTENT_URI, new String[] {
						Accounts._ID, Accounts.LOGIN }, null, null, null);
				if (c != null && c.moveToFirst()) {
					do {
						items.add(new Pair<Integer, String>(c.getInt(c
								.getColumnIndex(Accounts._ID)), c.getString(c
								.getColumnIndex(Accounts.LOGIN))));
					} while (c.moveToNext());
				}
				notifyDataSetChanged();
			}
		}

		
		public int getCount() {
			synchronized (items) {
				return items.size();
			}
		}
		

		@Override
		public String getItem(int position) {
			synchronized (items) {
				return items.get(position).second;
			}
		}

		@Override
		public long getItemId(int position) {
			synchronized (items) {
				return items.get(position).first;
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.accounts_list_item,
						null);
			}

			CheckedTextView text = (CheckedTextView) convertView;
			text.setText(items.get(position).second);
			// text.setChecked(manager.isActive(account.getID()));
			return convertView;
		}

	}

	private AccountsAdapter accountsListAdapter;
	private AccountsObserver accountsObserver;

	// FIXME
	class LoginDialog {

		private Dialog loginDialog;

		public LoginDialog(final String acc) {
			// FIXME  change type login field
			
			
			loginDialog = new Dialog(AccountsEditorActivity.this);
			loginDialog.setContentView(R.layout.login);
			loginDialog.setTitle(getText(R.string.addAcc)+" "+acc);
			
			EditText Login = (EditText) loginDialog.findViewById(R.id.Login);

				 if (acc.equals("ICQ"))	Login.setInputType(InputType.TYPE_CLASS_NUMBER);
			else if (acc.equals("JABBER")) Login.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
			
			Button ok_btn = (Button) loginDialog.findViewById(R.id.ButtonOK);
			ok_btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					EditText Login = (EditText) loginDialog
							.findViewById(R.id.Login);
					
					//EditText Login = (EditText) loginDialog.findViewById(R.id.Login);
					
						 						
					
					String login = Login.getText().toString();
					EditText pass_edit = (EditText) loginDialog
							.findViewById(R.id.Password);
					String password = pass_edit.getText().toString();
					String host = "login.icq.com";
					int port = 5190;

					ContentValues values = new ContentValues();
					values.put(Accounts.LOGIN, login);
					values.put(Accounts.PASSWORD, password);
					values.put(Accounts.HOST, host);
					values.put(Accounts.PORT, port);
					if (acc=="ICQ") {
					values.put(Accounts.TYPE, Accounts.TYPE_ICQ);}
					//for another protocol
					/* else {
					 * values.put(Accounts.TYPE, Accounts.TYPE_JABBER);}
					 * }
					 */
					getContentResolver().insert(Accounts.CONTENT_URI, values);

					loginDialog.dismiss();
				}

			});
			loginDialog.show();
		}
	}

	void initAccountsList() {
		ListView accountsList = (ListView) findViewById(R.id.AccountsList);
		accountsList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		accountsListAdapter = new AccountsAdapter(this);
		accountsList.setAdapter(accountsListAdapter);
		registerForContextMenu(accountsList);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.accounts_manager);

		setTitle(R.string.AccountsEditor);
		initAccountsList();
		accountsObserver = new AccountsObserver(new Handler());
		getContentResolver().registerContentObserver(Accounts.CONTENT_URI,
				true, accountsObserver);
		
		ImageView setting =  (ImageView) findViewById(R.id.accadd);
		setting.setOnClickListener(new View.OnClickListener(){  
            public void onClick(View v){
            	//startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
            	addAccount();
            }});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getContentResolver().unregisterContentObserver(accountsObserver);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.accounts_editor, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.add:
			addAccount();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(R.string.delete);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		final long accountID = accountsListAdapter.getItemId(info.position);
		final String itemName = accountsListAdapter.getItem(info.position);

		AlertDialog.Builder builder = new AlertDialog.Builder(
				AccountsEditorActivity.this);
		builder.setMessage(
				getString(R.string.account_delete_confirm) + " " + itemName
						+ "?")
				.setCancelable(false)
				.setPositiveButton(android.R.string.yes,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int id) {
								getContentResolver().delete(
										ContentUris
												.withAppendedId(
														Accounts.CONTENT_URI,
														accountID), null, null);
							}

						}).setNegativeButton(android.R.string.no, null).create().show();
		return true;
	}

	private void addAccount() {
		final String[] items = { "ICQ" , "Jabber" };
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.SelectProtocol);

		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int item) {
				switch (item) {
				case 0:
					// ICQ
					new LoginDialog(items[0]);
					break;
				case 1:
					// Jabber
					new LoginDialog(items[1]);
					break;
				}
			}
		});

		builder.create().show();
	}	
}
